#include "csg.h"

CSG::CSG()
{
    this->polygons=vector<MyPolygon>();
}

CSG* CSG::fromPolygons(vector<MyPolygon> polygons)
{
    CSG* csg = new CSG();
    csg->polygons = polygons;
    return csg;
}

CSG* CSG::clone()
{
    CSG* csg = new CSG();
    csg->polygons =vector<MyPolygon>(this->polygons);
    return csg;
}

vector<MyPolygon> CSG::toPolygons()
{
    return this->polygons;
}

CSG* CSG::csg_union(CSG* csg)
{
    Node* a = new Node(this->clone()->polygons);
    Node* b = new Node(csg->clone()->polygons);
    a->clipTo(b);
    b->clipTo(a);
    b->invert();
    b->clipTo(a);
    b->invert();
    a->build(b->allPolygons());
    vector<MyPolygon> ap = a->allPolygons();
    //vector<MyPolygon> bp = b->allPolygons();
    //ap.reserve(ap.size()+bp.size());
    //ap.insert(ap.end(), bp.begin(), bp.end());

    CSG* csg2=CSG::fromPolygons(ap);
    delete a;
    delete b;
    return csg2;
}

CSG* CSG::csg_subtract(CSG* csg)
{
    Node* a = new Node(this->clone()->polygons);
    Node* b = new Node(csg->clone()->polygons);
    a->invert();
    a->clipTo(b);
    b->clipTo(a);
    b->invert();
    b->clipTo(a);
    b->invert();
    a->build(b->allPolygons());
    a->invert();
    //a->invert();
    vector<MyPolygon> ap = a->allPolygons();
//    vector<MyPolygon> bp = b->allPolygons();
//    ap.reserve(ap.size()+bp.size());
//    ap.insert(ap.end(), bp.begin(), bp.end());

    CSG* csg2=CSG::fromPolygons(ap);
    delete a;
    delete b;
    return csg2;
}

CSG* CSG::csg_intersect(CSG* csg)
{
    Node* a = new Node(this->clone()->polygons);
    Node* b = new Node(csg->clone()->polygons);
    a->invert();
    b->clipTo(a);
    b->invert();
    a->clipTo(b);
    b->clipTo(a);
    a->build(b->allPolygons());
    a->invert();
    //a->invert();
    vector<MyPolygon> ap = a->allPolygons();
//    vector<MyPolygon> bp = b->allPolygons();
//    ap.reserve(ap.size()+bp.size());
//    ap.insert(ap.end(), bp.begin(), bp.end());

    CSG* csg2=CSG::fromPolygons(ap);
    delete a;
    delete b;
    return csg2;
}

CSG* CSG::inverse()
{
    CSG* csg = this->clone();
    for(vector<MyPolygon>::iterator it=csg->polygons.begin(); it!=csg->polygons.end(); ++it)
        it->invert();
    return csg;
}
